<?php

declare(strict_types=1);

namespace Modules\Order\Http\Controllers;

use AllowDynamicProperties;
use Api\Http\Controllers\WechatController;
use Api\Service\YidaService;
use Api\Service\YunyangService;
use Carbon\Carbon;
use Catch\Base\CatchController as Controller;
use EasyWeChat\Pay\Application;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Casts\Json;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Modules\Member\Models\Members;
use Modules\Order\Models\Orders;
use Modules\Shop\Models\Pivots\UserHasCoupons;

/**
 * 订单控制器
 */
#[AllowDynamicProperties] class OrdersController extends Controller
{
    public function __construct(
        protected readonly Orders $model
    )
    {
        $this->config = [
            'mch_id' => env('MCHID'),
            // 商户证书
            'private_key' => public_path() . '/cert/apiclient_key.pem',
            'certificate' => public_path() . '/cert/apiclient_cert.pem',

            // v3 API 秘钥
            'secret_key' => '762cea6bc6dd7ecd264cecddcf71fd26',

            // v2 API 秘钥 无

            // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
            // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
            'platform_certs' => [
                // 请使用绝对路径
                public_path() . '/cert/wechatpay_141E7C3415E93BF4155F6B9A5B3AC5A9C14FC8A5.pem',
            ],
            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http' => [
                'throw' => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.mch.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],
        ];
    }

    public function index(Request $request): mixed
    {
        $paid_status = $request->input('overweight_paid_status');
        $haocai_paid_status = $request->input('haocai_paid_status');
        $channel_type_code = $request->input('channel_type_code');
        $list = $this->model->setBeforeGetList(function ($query) use ($paid_status, $channel_type_code, $haocai_paid_status) {

            if ($paid_status == 1) {
                $query = $query->where('overweight_paid_at', '<>', 0)->where('is_overweight', 1);
            }
            if ($haocai_paid_status == 1) {
                $query = $query->where('haocai_paid_at', '<>', 0)->where('is_haocai', 1);
            }
            if ($paid_status == '0' && is_numeric($paid_status)) {
                $query = $query->where('overweight_paid_at', 0)->where('is_overweight', 1);
            }

            if ($haocai_paid_status == '0' && is_numeric($haocai_paid_status)) {
                $query = $query->where('haocai_paid_at', 0)->where('is_haocai', 1);
            }
            if($channel_type_code == 2){
                $query = $query->where('channel_type', 'yida' );
            }
            if($channel_type_code == 1){
                $query = $query->where(function ($query){
                    $query->where('channel_type', 'yunyang' )->orwhereNull('channel_type');
                });
            }
            return $query->with('coupon');
        })->getList()->toArray();
        foreach ($list['data'] as $k => $v) {
            if ($list['data'][$k]['is_overweight'] == 0) {
                $list['data'][$k]['overweight_paid_status'] = '';
            } elseif ($list['data'][$k]['is_overweight'] == 1 && $list['data'][$k]['overweight_paid_at'] == 0) {
                $list['data'][$k]['overweight_paid_status'] = 0;
            } else {
                $list['data'][$k]['overweight_paid_status'] = 1;
            }

            if ($list['data'][$k]['is_haocai'] == 0) {
                $list['data'][$k]['haocai_paid_status'] = '';
            } elseif ($list['data'][$k]['is_haocai'] == 1 && $list['data'][$k]['haocai_paid_at'] == 0) {
                $list['data'][$k]['haocai_paid_status'] = 0;
            } else {
                $list['data'][$k]['haocai_paid_status'] = 1;
            }
            if(!empty($list['data'][$k]['order_refund_sn'])){
                $list['data'][$k]['order_refund_status'] = 1;
            }else{
                $list['data'][$k]['order_refund_status'] = 0;
            }
        }
        return $list;
    }

    /**
     * @return mixed
     */
    public function store(Request $request)
    {
        $params = $request->all();
        $params['from'] = $params['from'] ?? 'admin'; // 后台添加
        return $this->model->storeBy($params);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id): mixed
    {
        return $this->model->firstBy($id)->makeHidden('password');
    }

    /**
     * @param $id
     * @param Request $request
     * @return mixed
     */
    public function update($id, Request $request): mixed
    {
        $params = $request->all();

        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id): mixed
    {
        return $this->model->deleteBy($id);
    }

    /**
     * @param $id
     * @return bool
     */
    public function enable($id)
    {
        return $this->model->toggleBy($id);
    }

    public function refund($id): mixed
    {


        $orderInfo = Orders::find($id);
        $wechat = new WechatController();
        $data['waybill'] = $orderInfo->waybill;
        $couponId = $orderInfo->coupon_id;
        if (empty($orderInfo->waybill)) {
            if(!empty($orderInfo->paid_at)){
                if(!empty($couponId)){
                    UserHasCoupons::where('user_id', $orderInfo->user_id)->where('coupon_id', $couponId)->update(['status' => 0]);
                }
                $result = $wechat->refundOrder($orderInfo->order_sn, $orderInfo->money);
                return $result;
            }
            return false;
        }
        if($orderInfo->channel_type == 'yida'){
            $json = (new YidaService())->cancelOrder($data);
            $result = json_decode($json, true);
            if($result['code'] == 200 ){
                $orderInfo->cancel_remark = '后台退款';
                $orderInfo->type = '已退款';
                $orderInfo->status = 2;
                $orderInfo->type_code = '5';
                $orderInfo->save();
                $wechat = new WechatController();
                if(!empty($orderInfo->overweight_paid_at)){
                    $refund = bcadd((string)$orderInfo->money,(string)$orderInfo->overweight_money);
                }else{
                    $refund = $orderInfo->money;
                }
                if(!empty($couponId)){
                    UserHasCoupons::where('user_id', $orderInfo->user_id)->where('coupon_id', $couponId)->update(['status' => 0]);
                }
                $wechat->refundOrder($orderInfo->order_sn,$refund) ;
                return '退款成功';
            }else{
                return '退款失败';
            }
        }else{
            $json = (new YunyangService)->cancelOrder($data);
            $result = json_decode($json, true);
            if ($result['code'] == 1) {
                $orderInfo->cancel_remark = '后台退款';
                $orderInfo->type = '已退款';
                $orderInfo->status = 2;
                $orderInfo->type_code = '5';
                $orderInfo->save();
                $wechat = new WechatController();
                if(!empty($orderInfo->overweight_paid_at)){
                    $refund = bcadd((string)$orderInfo->money,(string)$orderInfo->overweight_money);
                }else{
                    $refund = $orderInfo->money;
                }
                if(!empty($couponId)){
                    UserHasCoupons::where('user_id', $orderInfo->user_id)->where('coupon_id', $couponId)->update(['status' => 0]);
                }
                $wechat->refundOrder($orderInfo->order_sn,$refund) ;
                $data2['code'] = 10000;
                $data2['data'] = $id;
                $data2['message'] = '退款成功';
                return $data2;
            } else {
                return $result['message'];
            }
        }


    }

    public function overweightPush(Request $request)
    {
        $id = $request->post('id');
        $type = $request->post('type');
        if ($type == 2) {
            $orderList = $this->model->where('overweight_paid_at', 0)->get();
        } else {
            $orderList = $this->model->whereIn('id', $id)->get();
        }

        foreach ($orderList as $orderInfo) {
            $openId = Members::where('id', $orderInfo->user_id)->value('open_id');
            $is_overweight = $orderInfo->is_overweight;
            $paid_at = $orderInfo->overweight_paid_at;
            $data['data'] = $id;
            if ($is_overweight != 1 || $paid_at != 0) {
                continue;
            }
            $wechat = new WechatController();
            $overWeight = $orderInfo->cal_weight;
            //小程序提醒超重
            $message = [];
            $message['thing1'] = ['value' => $orderInfo->tag_type];
            $message['character_string2'] = ['value' => $orderInfo->waybill];
            $message['number4'] = ['value' => $overWeight];
            $message['amount5'] = ['value' => $orderInfo->overweight_money];
            $message['thing6'] = ['value' => '请及时支付超重费用,以免影响寄件'];
            $obj = (object)$message;
            $wechat = new WechatController();
            $page = 'pages/user/addMoney';
            $wechat->sendMessage('rYgOcm2rCdA2ZVX-bufrhRkM2QYHxZ7NRURrqt2Pyjw', $openId, $obj, $page);
        }


        $data['code'] = 10000;
        $data['message'] = '推送成功';
        return $data;

    }

    public function sendMessage(Request $request)
    {
        $time = sprintf('%03d', round(microtime(true) * 1000));
        $accountSid = 'cb2612587adb1d4771d5b0edf783b307';
        $token = 'fbea5ea14fd94ba864a97dde924222be';
        $signStr = $accountSid.$token.$time;
        $sign = md5($signStr);
        $url = 'https://openapi.danmi.com/textSMS/sendSMS/V1';
        $data = [];
        $data['accountSid'] = $accountSid;
        $data['templateid'] = '1000000019299';
        $type = $request->post('type');
        $id = $request->post('id');
        if ($type == 2) {
            $orderList = $this->model->where('overweight_paid_at', 0)->where('is_overweight',1)->get();
            $haocaiList = $this->model->where('haocai_paid_at', 0)->where('is_haocai',1)->get();
        } else {
            $orderList = $haocaiList = $this->model->whereIn('id', $id)->get();
        }

        foreach ($orderList as $orderInfo) {

            $is_overweight = $orderInfo->is_overweight;
            $mobile = Members::where('id',$orderInfo->user_id)->value('mobile');
            $paid_at = $orderInfo->overweight_paid_at;
            if ($is_overweight != 1 || $paid_at != 0) {
                continue;
            }

            $overWeight = bcsub((string)$orderInfo->cal_weight,(string)$orderInfo->weight);
            //小程序提醒超重
            $data['to'] = $mobile;
            $data['timestamp'] = $time;
            $data['sig'] = $sign;
            $data['param'] = $orderInfo->waybill.','.$overWeight.','.$orderInfo->overweight_money;
            $client = new Client(['timeout' => 10, 'verify' => false]);
            $headers=['Content-Type'=>"application/x-www-form-urlencoded"];
            $response=$client->post($url,[
                'headers'=>$headers,
                'form_params'=>$data
            ]);

        }

        foreach ($haocaiList as $orderInfo) {
            $is_haocai = $orderInfo->is_haocai;
            $mobile = Members::where('id',$orderInfo->user_id)->value('mobile');
            $paid_at = $orderInfo->haocai_paid_at;
            if ($is_haocai != 1 || $paid_at != 0) {
                continue;
            }
            //耗材费补缴
            $data['to'] = $mobile;
            $data['timestamp'] = $time;
            $data['sig'] = $sign;
            $data['templateid'] = '1000000026341';
            $data['param'] = $orderInfo->waybill.','.$orderInfo->haocai_money;
            $client = new Client(['timeout' => 10, 'verify' => false]);
            $headers=['Content-Type'=>"application/x-www-form-urlencoded"];
            $response=$client->post($url,[
                'headers'=>$headers,
                'form_params'=>$data
            ]);
        }
        $data['code'] = 10000;
        $data['message'] = '推送成功';
        return $data;
    }
}

